<template>
  <!--  静态模态框 -->
  <div class="modal">
    <!-- 遮罩层 -->
    <div class="mask" @click="changeisShowloginModal(false)"></div>
    <div class="loginbox">
      <!-- 关闭按钮 -->
      <div class="close" @click="changeisShowloginModal(false)"></div>
      <div class="nav">
        <!-- 手机号码登陆 -->
        <p :class="{ active: isShowContent }" @click="isShowContent = true">
          手机号码登陆
        </p>
        <!-- 微信扫码登陆 -->
        <!-- <p :class="{ active: !isShowContent }" @click="isShowContent = false">
          微信扫码登陆
        </p> -->
        <p :class="{ active: !isShowContent }" @click="showQrCode">扫码</p>
      </div>
      <!-- 内容区域 -->
      <div class="content">
        <!-- 手机号码登陆框内内容 -->
        <div class="phonelogin" v-show="isShowContent">
          <div class="row">
            <input
              type="text"
              class="ipt"
              placeholder="请输入手机号"
              ref="phone"
              v-model="phoneNumber"
            />
          </div>
          <div class="row">
            <!-- 向右滑动模块 -->
            <slide-verify
              :l="42"
              :r="20"
              :w="362"
              :h="140"
              @success="onSuccess"
              @fail="onFail"
              @refresh="onRefresh"
              :style="{ width: '100%' }"
              class="slide-box"
              ref="slideBlock"
              :slider-text="msg"
            ></slide-verify>
          </div>
          <div class="row">
            <input
              type="text"
              class="ipt"
              placeholder="请输入短信验证码"
              v-model="code"
            />
            <button class="btn btnlogin">
              <span v-show="!isShowCount" @click="getCode">获取验证码</span>
              <span v-show="isShowCount">{{ count }} s</span>
            </button>
          </div>
          <div class="row">
            <button class="btn btnlog" @click="submitFn">登陆</button>
          </div>
        </div>
        <!--  微信框内内容 -->
        <div class="wechat" v-show="!isShowContent" id="weixin">
          微信框内内容
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapMutations, mapActions } from "vuex";
// 引入抽取工具
import { validateTelephoneNumber } from "@/utils";
import { SendSMSAPI, phoneReginAPI, bingPhoneAPI } from "@/request/api";

export default {
  data() {
    return {
      isShowContent: true,
      msg: "向右滑动",
      phoneNumber: "", //手机号
      count: 60, //计数值
      isShowCount: false, //是否显示倒计时
      code: "",
    };
  },
  methods: {
    ...mapMutations({
      changeisShowloginModal: "showModal/changeisShowloginModal",
      changeLsLogined: "loginStatus/changeLsLogined",
      changeisshowToast: "showToast/changeisshowToast",
    }),
    ...mapActions({
      asyncIsShowToast: "showToast/asyncIsShowToast",
      asyncChangeuserInfo: "userInfo/asyncChangeuserInfo",
    }),
    // 拼图成功
    onSuccess(times) {
      let ms = (times / 1000).toFixed(1);
      this.msg = "login success, 耗时 " + ms + "s";
    },
    // 拼图失败
    onFail() {
      this.onRefresh(); // 重新刷新拼图
    },
    // 拼图刷新
    onRefresh() {
      this.msg = "再试一次";
    },
    countdown() {
      this.isShowCount = true;
      let timer = setInterval(() => {
        this.count--;
        if (this.count == 0) {
          clearInterval(timer);
          this.isShowCount = false;
          this.count = 60;
        }
      }, 1000);
    },

    // 提取一个校验手机号和滑块的方法
    toVerify() {
      // 手机号验证
      if (!validateTelephoneNumber(this.phoneNumber)) {
        // alert("请输入正确的手机号码");
        this.$refs.phone.focus();
        // 弹出框显示
        // this.changeisshowToast({
        //   show: true,
        //   msg: "请输入正确的手机号码",
        //   Type: "success",
        // });
        // 隐藏
        this.asyncIsShowToast({
          show: true,
          msg: "请输入正确的手机号码",
          type: "danger",
        });
        return false;
      }
      // 滑块验证
      // if (this.msg == "再试一次" || this.msg == "向右滑动") {
      //   // alert("请先进行滑块操作");
      //   // this.changeisshowToast({
      //   //   show: true,
      //   //   msg: "请先进行滑块操作",
      //   //   Type: "danger",
      //   // });
      //   //优化后进行的显示操作
      //   this.asyncIsShowToast({
      //     show: true,
      //     msg: "请先进行滑块操作",
      //     type: "danger",
      //   });
      //   return false;
      // }

      return true;
    },
    // 获取验证码
    async getCode() {
      // console.log(1);

      // 拼图滑块验证不同过就 return
      if (!this.toVerify()) {
        return;
      }
      // 3、验证成功后，发起请求，获取验证码成功，则进行倒计时
      let res = await SendSMSAPI({
        phone: this.phoneNumber.trim(),
      });
      // console.log("发送验证码成功", res);
      // if (!res) return;
      // alert("发送成功");
      this.asyncIsShowToast({
        show: true,
        msg: "发送成功",
        type: "danger",
      });

      this.countdown();
      // this.countdown();
      this.isShowCount = true;
      // 4. 发起登录请求
    },

    // 点击登录按钮
    async submitFn() {
      // 以msg文字内容来判断是否进行饼图操作
      // if (this.msg == "再试一次" || this.msg == "向右滑动") {
      //   alert("请滑动拼图");
      //   return;
      // }

      // 校验图片
      if (!this.toVerify()) {
        return;
      }
      if (this.code.trim() == "") {
        alert("请输入手机验证码!");
        return;
      }
      // 4. 发起登录请求
      //  如果本地使用了uuid，则调用，否则绑定手机号请求
      let uuid = localStorage.getItem("uuid");
      let res = null;
      if (uuid) {
        // console.log("发起绑定手机号请求...");
        res = await bingPhoneAPI({
          verifyCode: this.code,
          phone: this.phoneNumber,
          uuid,
        });
      } else {
        // 普通手机号登录请求
        // console.log("发起一下登录请求。。。");
        res = await phoneReginAPI({
          verifyCode: this.code,
          phone: this.phoneNumber,
        });
      }
      if (!res) {
        return;
      }
      localStorage.removeItem("uuid");
      //           2. 删除地址栏中code
      this.$router.push(this.$route.path);

      //手机验证码校验效果
      if (this.code.trim() == "") {
        // alert("验证码请输入");
        this.asyncIsShowToast({
          show: true,
          msg: "请输入验证码",
          type: "danger",
        });
        return;
      }
      // 登陆接口
      //  定义一个res接受接口
      res = await phoneReginAPI({
        verifyCode: this.code,
        phone: this.phoneNumber,
      });
      // 1. 弹出登录框
      alert("登陆成功");
      // 2.存储token在本地存储中
      localStorage.setItem("x-auth-token", res["x-auth-token"]);
      // 3.隐藏登陆模态框
      this.changeisShowloginModal(false);
      // 引入vuex中的接口，显示购物小车车
      this.changeLsLogined(true);

      //登陆成功之后拿到用户信息
      // let userRes = await userProfilesAPI();
      // if (!userRes) return;
      // console.log("获取用户信息", userRes);

      // 更新用户的信心
      this.asyncChangeuserInfo();
    },
    // 点击显示微信二维码登录按钮
    showQrCode() {
      this.isShowContent = false;
      //获取二维码 并展示
      // 申请微信登录二维码
      let _this = this;
      new WxLogin({
        id: "weixin",
        appid: "wx67cfaf9e3ad31a0d", // 这个appid要填死
        scope: "snsapi_login",
        // 扫码成功后重定向的接口
        redirect_uri: "https://sc.wolfcode.cn/cms/wechatUsers/shop/PC",
        // state填写编码后的url
        state: encodeURIComponent(
          window.btoa("http://127.0.0.1:8080" + _this.$route.path)
        ),
        // 调用样式文件
        href: "data:text/css;base64,Lyogd3hsb2dpbi5jc3MgKi8NCi5pbXBvd2VyQm94IC50aXRsZSwgLmltcG93ZXJCb3ggLmluZm97DQogIGRpc3BsYXk6IG5vbmU7DQp9DQoNCi5pbXBvd2VyQm94IC5xcmNvZGV7DQogIG1hcmdpbi10b3A6IDIwcHg7DQp9",
      });
    },
  },
};
</script>

<style lang="less" scoped>
.modal {
  width: 100%;
  height: 100%;
  position: fixed;
  left: 0;
  bottom: 0;
  //   background-color: aquamarine;
  .mask {
    width: 100%;
    height: 100%;
    background-color: rgba(51, 32, 32, 0.4);
  }
  .loginbox {
    position: absolute;
    margin: auto;
    width: 555px;
    height: 423px;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: url("../assets/img/login-box-bg.png");

    // 模态框样式
    .nav {
      display: flex;
      justify-content: center;
      margin-top: 30px;
      // color: red;
      color: #999;
      p {
        padding: 0 10px;
        cursor: pointer;
        &.active {
          color: black;
        }
      }
    }
  }
  //  模态框内容区域
  .content {
    width: 350px;
    height: 300px;
    margin: 20px auto;
    // background-color: red;
    // 里面的输入框样式
    .row {
      display: flex;
      margin-bottom: 20px;
      .ipt {
        flex: 1;
        height: 45px;
        outline: none;
        padding-left: 10px;
      }
      //获取验证码按钮左边距
      .btnlogin {
        margin-left: 10px;
      }
      .btn {
        background-color: rgb(14, 171, 233);
        border: none;
        line-height: 45px;
        cursor: pointer;
        width: 80px;
      }
      // 登陆框样式
      .btnlog {
        width: 100%;
      }
    }
  }
  .close {
    position: absolute;
    top: 20px;
    right: 60px;
    height: 22px;
    width: 22px;
    cursor: pointer;
    background: url("../assets/img/close.png");
  }
}

// 向右滑动样式
/deep/.slide-box {
  width: 100%;
  position: relative;
  box-sizing: border-box;
  canvas {
    position: absolute;
    left: 0;
    top: -120px;
    display: none;
    width: 100%;
    box-sizing: border-box;
  }
  .slide-verify-block {
    width: 85px;
    height: 136px;
  }
  .slide-verify-refresh-icon {
    top: -120px;
    display: none;
  }
  &:hover {
    canvas {
      display: block;
    }
    .slide-verify-refresh-icon {
      display: block;
    }
  }
}
</style>